# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from google.appengine.api import urlfetch
from xml.dom import minidom

import django
from django import http
from django import shortcuts
import urllib
import time
import datetime



class RaceX(db.Model):

  name = db.StringProperty(required=True);
  date = db.DateProperty(required=True);
  time = db.TimeProperty(required=True);
  location = db.StringProperty(required=True);
  distance_in_miles = db.FloatProperty(required=True);

#  race = db.StringProperty(required=True,default='2009 Boston Marathon',choices=['2009 Boston Marathon', '2008 Prospect Park Cherry Tree 10 Miler', 'Prospect Park Duathlon & Gotham Cup Club Challenge Sunday, November 9, 2008' ])
#  first = db.StringProperty(required=True)
#  last = db.StringProperty(required=True)
#  age = db.IntegerProperty(required=True,default=20,choices=[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99])
#  gender = db.StringProperty(required=True,default='M',choices=['M','F'])
#  division = db.StringProperty(required=True,default='Open',choices=['Open', 'Clydesdale', 'Athena' ])
  racedirector = db.UserProperty()
  payment_company = db.StringProperty(required=True,default='Google Checkout',choices=['Google Checkout', 'Paypal' ])
  payment_company_id = db.StringProperty(required=True)
  payment_cost = db.FloatProperty(required=True)
  nonprofit = db.BooleanProperty(required=False)
  website = db.StringProperty()
  comments = db.TextProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  ip = db.StringProperty()

#class Result(db.Model):
class Race(db.Model):

  first  = db.StringProperty(required=True);
  last  = db.StringProperty(required=True);
  age = db.IntegerProperty(required=True,default=20,choices=[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99])
  #age = db.IntegerProperty(required=True)
  gender = db.StringProperty(required=True,default='M',choices=['M','F'])
  #gender = db.StringProperty(required=True)
  #age = db.StringProperty(required=True);
  agegradedpercent  = db.FloatProperty(required=False);
  datasource  = db.StringProperty(required=False);
  date  = db.StringProperty(required=False);
  racename  = db.StringProperty(required=True);
  racedate  = db.DateProperty(required=True);
  distanceInMiles  = db.FloatProperty(required=False);
  distance_in_miles  = db.FloatProperty(required=True);
  #gender  = db.StringProperty(required=True);
  guntime  = db.StringProperty(required=True);
  nettime  = db.StringProperty(required=True);
  pace  = db.StringProperty(required=False);
  overallplace  = db.IntegerProperty(required=False);
  genderplace  = db.IntegerProperty(required=False);
  ageplace  = db.IntegerProperty(required=False);
  team  = db.StringProperty(required=False);
  training = db.BooleanProperty(required=False)
  comments = db.TextProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  ip = db.StringProperty()
  racedirector = db.UserProperty()


class Entry(db.Model):

  first = db.StringProperty(required=True)
  last = db.StringProperty(required=True)
  age = db.IntegerProperty(required=True,default=20,choices=[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99])
  gender = db.StringProperty(required=True,default='M',choices=['M','F'])
  shirt_size = db.StringProperty(default='Medium',choices=['Small', 'Medium', 'Large', 'XL' ])
  division = db.StringProperty(required=True,default='Open',choices=['Open', 'Clydesdale', 'Athena' ])
  racedirector = db.UserProperty()
  comments = db.TextProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  ip = db.StringProperty()
  raceid = db.IntegerProperty()

class RaceForm(djangoforms.ModelForm):
  class Meta:
    model = Race
    exclude = ['date', 'racedirector', 'created', 'modified', 'ip', 'datasource', 'distanceInMiles']

class EntryForm(djangoforms.ModelForm):
  class Meta:
    model = Entry
    exclude = ['racedirector', 'created', 'modified', 'ip', 'raceid']
    #exclude = ['racedirector', 'created', 'modified', 'ip']



def parse( url ) :
   result = urlfetch.fetch(url)
   if result.status_code == 200:
           return minidom.parseString(result.content)

def weather_for_zip(zip_code):
  WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
  WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
  url = WEATHER_URL % zip_code
  dom = parse(url)
  forecasts = []
  for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'):
	forecasts.append({
	    'date': node.getAttribute('date'),
	    'low': node.getAttribute('low'),
	    'high': node.getAttribute('high'),
	    'condition': node.getAttribute('text')
	})
  return {
	'forecasts': forecasts,
	'title': dom.getElementsByTagName('title')[0].firstChild.data
  }

def process_xml2db(datasource,user,request):
  #RESULTS_URL = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/nyrrWSXExportGoldenXML.jsp'
  RESULTS_URL = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/datasourceExportXML.jsp?datasource=%s' % datasource
#WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
  url = RESULTS_URL
  dom = parse(url)

  q = db.GqlQuery("SELECT * FROM Race where datasource = :1", 'googleapp:%s' % user)
  results = q.fetch(1000)
  for result in results:
    result.delete()

  results = []
  for node in dom.getElementsByTagName('result'):
    results.append({ 'racename': node.getAttribute('racename'), 'racedate': node.getAttribute('racedate') })
    #print node.getAttribute('racename')
    #print node.getAttribute('distance_in_miles')

    racedate=time.strptime(node.getAttribute('racedate'), "%Y-%m-%d %H:%M:%S.0")
    race = Race(distance_in_miles=float(node.getAttribute('distance_in_miles')), 
	    date=node.getAttribute('date'),
	    #racedate=datetime.fromtimestamp(time.strptime(node.getAttribute('racedate'), "%Y-%m-%d %H:%M:%S.0"))
	    #racedate=datetime.date( 2008, 1, 1)
	    racedate=datetime.date(racedate.tm_year, racedate.tm_mon, racedate.tm_mday),
	    guntime=node.getAttribute('guntime'),
	    nettime=node.getAttribute('nettime'),
	    pace=node.getAttribute('pace'),
	    distanceInMiles=float(node.getAttribute('distanceInMiles')),
	    gender=node.getAttribute('gender'),
	    first=node.getAttribute('first'),
	    last=node.getAttribute('last'),
	    racename=node.getAttribute('racename'),
	    overallplace=int(node.getAttribute('overallplace')),
	    genderplace=int(node.getAttribute('genderplace')),
	    ageplace=int(node.getAttribute('ageplace')),
	    age=int(node.getAttribute('age')),
	    team=node.getAttribute('team'),
	    comments=node.getAttribute('comments'),
	    datasource=datasource,
	    )
    race.date = str(race.racedate)
    race.racedirector = user
    race.ip = request.META["REMOTE_ADDR"]
    race.put()

  #return dom.toxml()
  return { 'results': results, 'title': 'results' }

def get_results_from_database(datasource):
  RESULTS_URL = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/datasourceExportXML.jsp?datasource=%s' % datasource
  url = RESULTS_URL
  dom = parse(url)
  x = dom.createElement("foo")  # creates <foo />
  dom.childNodes[0].appendChild(x)  # appends at end of 1st child's children

  results = []
  for node in dom.getElementsByTagName('result'):
	results.append({
	    'racename': node.getAttribute('racename'),
	    'racedate': node.getAttribute('racedate')
	})
  return dom.toxml()
  #return { 'results': results, 'title': 'results' }

def get_results_for_datasource(datasource):
  #RESULTS_URL = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/nyrrWSXExportGoldenXML.jsp'
  RESULTS_URL = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/datasourceExportXML.jsp?datasource=%s' % datasource
#WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
  url = RESULTS_URL
  dom = parse(url)
  x = dom.createElement("foo")  # creates <foo />
  dom.childNodes[0].appendChild(x)  # appends at end of 1st child's children

  results = []
  for node in dom.getElementsByTagName('result'):
	results.append({
	    'racename': node.getAttribute('racename'),
	    'racedate': node.getAttribute('racedate')
	})
  return dom.toxml()
  #return { 'results': results, 'title': 'results' }

def get(request):
  """get xml."""
  #print 'Content-Type: text/plain'
  #print 'Content-Type: text/xml'
  #print ''
#print weather_for_zip('94089')
  #print get_results_for_datasource('gxoogleapp:fedex1')
  return http.HttpResponse(get_results_for_datasource('gxoogleapp:fedex1'), mimetype="text/xml")
  #return http.HttpResponseRedirect('/')

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)



def index(request):
  """Request / -- show all races."""

  user = users.GetCurrentUser()
  #if user is None:
    #return http.HttpResponseForbidden('You must sign in to view your list.')
  #races = db.GqlQuery('SELECT * FROM Race ORDER BY created DESC')
  races = db.GqlQuery('SELECT * FROM Race WHERE datasource = :1 ORDER BY created DESC', 'googleapp:%s' % user)
  return respond(request, user, 'list', {'races': races})

def process_db2xml(request):
  """process db2xml"""
  document = """<results></results>"""
  dom = minidom.parseString(document)

  user = users.GetCurrentUser()
  #print user
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to perform this operation. <a href="/">Continue.</a>')
  else:
    q = db.GqlQuery("SELECT * FROM Race where datasource = :1", 'googleapp:%s' % user)
    results = q.fetch(1000)
    for result in results:
      node = dom.createElement("result")  # creates <foo />
      node.setAttribute('age', str(result.age))
      node.setAttribute('agegradedpercent', checkvalue(result.agegradedpercent))
      node.setAttribute('ageplace', checkvalue(result.ageplace))
      node.setAttribute('comments', str(result.comments))
      node.setAttribute('created', str(result.created))
      node.setAttribute('datasource', result.datasource)
      node.setAttribute('date', result.date)
      node.setAttribute('distanceInMiles', str(result.distanceInMiles))
      node.setAttribute('distance_in_miles', str(result.distance_in_miles))
      node.setAttribute('first', result.first)
      node.setAttribute('gender', result.gender)

      #node.setAttribute('genderplace', str(result.genderplace))
      node.setAttribute('genderplace', checkvalue(result.genderplace))

      node.setAttribute('guntime', result.guntime)
      node.setAttribute('ip', result.ip)
      node.setAttribute('last', result.last)
      node.setAttribute('modified', str(result.modified))
      node.setAttribute('nettime', result.nettime)

      node.setAttribute('overallplace', checkvalue(result.overallplace))
      node.setAttribute('pace', checkvalue(result.pace))


      node.setAttribute('racedate', str(result.racedate))
#      node.setAttribute('racedirector', result.racedirector)
      node.setAttribute('racename', result.racename)
      node.setAttribute('team', checkvalue(result.team))
      node.setAttribute('training', str(result.training))
      #node.setAttribute('training', 'XXX')
      dom.childNodes[0].appendChild(node)  # appends at end of 1st child's children
    #print q

    url = "http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/buildpost.jsp?datasource=googleapp:%s" % user
    #xml = {"":dom.toxml()}
    #form_data = urllib.urlencode(xml)
    #form_data = xml

    result = urlfetch.fetch(url=url, payload=dom.toxml(), method=urlfetch.POST, headers={'Content-Type': 'text/xml'})
    return dom


def db2xml(request):
  """db2xml"""
  user = users.GetCurrentUser()
  dom = process_db2xml(request)
  url = "http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/buildpost.jsp?datasource=googleapp:%s" % user
  result = urlfetch.fetch(url=url, payload=dom.toxml(), method=urlfetch.POST, headers={'Content-Type': 'text/xml'})

  for node in dom.getElementsByTagName('result'):
    first = node.getAttribute('first')
    last = node.getAttribute('last')
  #print first
  #print last

  #return http.HttpResponse(dom.toxml(), mimetype="text/xml")
  #return http.HttpResponseRedirect('/')
  #return http.HttpResponse('Data exported. <br/><a href="/">Continue.</a> <br/><br/> or <br/><br/><a target="_blank" href="http://run.wsxnyc.org">See results at http://run.wsxnyc.org</a><br/><iframe src="http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/chartme.jsp?first=%s&last=%s" width="600" height="500" marginwidth="0" marginheight="0" frameborder="0" scrolling="no"></iframe> '% ('ralph', 'yozzo') )
  return http.HttpResponse('Data exported. <br/><a href="/">Continue.</a> <br/><br/> or <br/><br/><a target="_blank" href="http://run.wsxnyc.org">See results at http://run.wsxnyc.org</a><br/><iframe src="http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/chartme.jsp?first=%s&last=%s" width="600" height="500" marginwidth="0" marginheight="0" frameborder="0" scrolling="no"></iframe> '% (first, last) )

#def deleteall(request):
  #q = db.GqlQuery("DROP TABLE Race")
  #q = db.GqlQuery("SELECT * FROM Race")
  #results = q.fetch(10)
  #for result in results:
    #result.delete()


def xml2db(request):
  """xml2db (no duplicates)"""

  #q = db.GqlQuery("SELECT * FROM Race")
  #results = q.fetch(10)
  #for result in results:
	#result.delete()

  user = users.GetCurrentUser()
  #print user
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to perform this operation.')
  else:
    #return http.HttpResponse(get_results_for_datasource('gxoogleapp:fedex1'), mimetype="text/xml")
    #return http.HttpResponse(process_xml2db('gxoogleapp:fedex1'), mimetype="text/plain")

    #return http.HttpResponse(process_xml2db('googleapp:fedex1',user,request))

    #return http.HttpResponse(process_xml2db('googleapp:%s' % user, user,request))
    process_xml2db('googleapp:%s' % user, user,request)
    return http.HttpResponseRedirect('/')

def db2xmlx(request):
  """dump xml for datasource"""

  #q = db.GqlQuery("SELECT * FROM Race")
  #results = q.fetch(10)
  #for race in results:
    #race.training = False
    #race.put()
  dom = process_db2xml(request)
  return http.HttpResponse(dom.toxml(), mimetype="text/xml")

def edit(request, race_id):
  """Create or edit an entry.  GET shows a blank form, POST processes it."""

  #q = db.GqlQuery("SELECT * FROM Race")
  #results = q.fetch(10)
  #for result in results:
	#result.delete()

  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to perform this operation.')

  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No race exists with that key (%r)' %
                                       race_id)
    if race.racedirector != user:
		return http.HttpResponseNotFound('You are not the owner of this race')

  form = RaceForm(data=request.POST or None, instance=race)

  if not request.POST:
    return respond(request, user, 'race', {'form': form, 'race': race})

  errors = form.errors
  if not errors:
    try:
      race = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'race', {'form': form, 'race': race})

  if not race.racedirector:
    race.racedirector = user
  race.ip = request.META["REMOTE_ADDR"]
  race.distanceInMiles = race.distance_in_miles
  race.datasource = 'googleapp:%s' % user
  race.date = str(race.racedate)
  race.put()

  return http.HttpResponseRedirect('/')

def new(request):
  """Create an entry.  GET shows a blank form, POST processes it."""
  return edit(request, None)

def entry(request, race_id):
  """Create or edit an entry.  GET shows a blank form, POST processes it."""

  user = users.GetCurrentUser()
  #if user is None:
    #return http.HttpResponseForbidden('You must be signed in to add or edit an entry')

  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No entry exists with that key (%r)' %
                                       race_id)
  entry = None

  form = EntryForm(data=request.POST or None, instance=entry)

  if not request.POST:
	  #print 'not request.POST'
	  return respond(request, user, 'entry', {'form': form, 'entry': entry, 'race':race})

  errors = form.errors
  if not errors:
    try:
      entry = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
	return respond(request, user, 'entry', {'form': form, 'entry': entry, 'race':race})

  if not entry.racedirector:
    entry.racedirector = user
  entry.ip = request.META["REMOTE_ADDR"]
  entry.raceid = int(race_id)
  entry.put()

  #return http.HttpResponseRedirect('/')
  return respond(request, user, 'payment', {'entry': entry, 'race':race})

def listentries(request, race_id):
  """Request / -- show all entries for a race."""

  user = users.GetCurrentUser()
  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No entry exists with that key (%r)' %
                                       race_id)
  entries = db.GqlQuery('SELECT * FROM Entry WHERE raceid = :1 ORDER BY created DESC', int(race_id))
  #entries = db.GqlQuery('SELECT * FROM Entry ORDER BY created DESC')
  return respond(request, user, 'listentries', {'entries': entries, 'race':race})


def about(request):
    return shortcuts.render_to_response("static/about.html")

def help(request):
    return shortcuts.render_to_response("static/help.html")

def entryx_old_1(request, race_id):
  """Create or edit an entry.  GET shows a blank form, POST processes it."""

  user = users.GetCurrentUser()
  #if user is None:
    #return http.HttpResponseForbidden('You must be signed in to add or edit an entry')

  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No entry exists with that key (%r)' %
                                       race_id)
  entry = None

  form = EntryForm(data=request.POST or None, instance=entry)

  if not request.POST:
	  #print 'not request.POST'
	  return respond(request, user, 'entryx', {'form': form, 'entry': entry, 'race':race})

  errors = form.errors
  if not errors:
    try:
      entry = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
	return respond(request, user, 'entryx', {'form': form, 'entry': entry, 'race':race})

  if not entry.racedirector:
    entry.racedirector = user
  entry.ip = request.META["REMOTE_ADDR"]
  entry.raceid = int(race_id)

  # call checkout procedure
  
  #url = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/%r" % (race.payment_company_id,)
  url = "https://checkout.google.com/api/checkout/v2/merchantCheckout/Merchant/%r/diagnose" % (race.payment_company_id,)
  form_fields = {
		"item_description_1": race.comments,
		"item_quantity_1": "1",
		"item_price_1": race.payment_cost,
		"item_currency_1": "USD",
		"_charset_": "utf-8",
  }
  xml = {"":'<?xml version="1.0" encoding="UTF-8"?> <checkout-shopping-cart xmlns="http://checkout.google.com/schema/2"> <shopping-cart> <items> <item> <item-name>HelloWorld 2GB MP3 Player</item-name> <item-description>HelloWorld, the simple MP3 player</item-description> <unit-price currency="USD">159.99</unit-price> <quantity>1</quantity> </item> </items> </shopping-cart> <checkout-flow-support> <merchant-checkout-flow-support> <shipping-methods> <flat-rate-shipping name="SuperShip Ground"> <price currency="USD">9.99</price> </flat-rate-shipping> </shipping-methods> </merchant-checkout-flow-support> </checkout-flow-support> </checkout-shopping-cart>'}
  form_data = urllib.urlencode(xml)
  result = urlfetch.fetch(url=url,
  			payload=form_data,
  			method=urlfetch.POST,
  			headers={'Content-Type': 'application/x-www-form-urlencoded'})

  print result
  print result.content
  entry.put()

  return http.HttpResponseRedirect('/')
  #return respond(request, user, 'payment', {'entry': entry, 'race':race})

def entryx(request, race_id):
  """Create or edit an entry.  GET shows a blank form, POST processes it."""

  user = users.GetCurrentUser()
  #if user is None:
    #return http.HttpResponseForbidden('You must be signed in to add or edit an entry')

  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No entry exists with that key (%r)' %
                                       race_id)
  entry = None

  form = EntryForm(data=request.POST or None, instance=entry)

  if not request.POST:
	  #print 'not request.POST'
	  return respond(request, user, 'entryx', {'form': form, 'entry': entry, 'race':race})

  errors = form.errors
  if not errors:
    try:
      entry = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
	return respond(request, user, 'entryx', {'form': form, 'entry': entry, 'race':race})

  if not entry.racedirector:
    entry.racedirector = user
  entry.ip = request.META["REMOTE_ADDR"]
  entry.raceid = int(race_id)

  # call checkout procedure
  
  url = 'http://www.google.com'
  payload = 'foo=bar'
  result = urlfetch.fetch(url, payload) 

#  url = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/%r" % (race.payment_company_id,)
#  form_fields = {
#		  "item_name_1": '%r %r %r %r %r' %(race.name,race.distance_in_miles,race.date,race.time,race.location,),
#		"item_description_1": race.comments,
#		"item_quantity_1": "1",
#		"item_price_1": race.payment_cost,
#		"item_currency_1": "USD",
#		"_charset_": "utf-8",
#  }
#  form_data = urllib.urlencode(form_fields)
#  result = urlfetch.fetch(url=url,
#  			payload=form_data,
#  			method=urlfetch.POST,
#  			headers={'Content-Type': 'application/x-www-form-urlencoded'})

  #print result
  print result.content
  entry.put()

  return http.HttpResponseRedirect('/')
  #return respond(request, user, 'payment', {'entry': entry, 'race':race})

def checkvalue(variable):
  if variable is None:
      return ''
  else:
      return str(variable)

def delete(request, race_id):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to perform this operation.')

  race = None
  if race_id:
    race = Race.get(db.Key.from_path(Race.kind(), int(race_id)))
    if race is None:
      return http.HttpResponseNotFound('No race exists with that key (%r)' %
                                       race_id)
    if race.racedirector != user:
		return http.HttpResponseNotFound('You are not the owner of this race')
    race.delete()
  return http.HttpResponseRedirect('/')

